<?php
/**
 * Created by PhpStorm.
 * User: aiChenK
 * Date: 2019-01-18
 * Time: 15:55
 */

namespace Helpers;

class Page
{

    /**
     * 原生sql分页
     *
     * @param $sql
     * @param int $page
     * @param int $size
     * @return array
     * @throws \Exception
     *
     * create by ck 20190118
     */
    public static function runSqlPage($sql, $page = 1, $size = 50)
    {
        $db     = Di::get()->db;
        $offset = $size * ($page - 1);
        $query  = $sql;
        if (!preg_match('/^select(.*) from/is', $sql, $columns)) {
            throw new \Exception('sql语句解析失败');
        }
        if (stristr($sql, 'group by')) {
            $totalQuery = "select count(*) as total from ({$sql}) as t";
        } else {
            $totalQuery = preg_replace(
                '/^select(.*) from/is',
                'select count(*) as total from',
                $sql,
                1
            );
        }
        $total = $db->fetchOne($totalQuery)['total'];
        if ($size) {
            $query .= " LIMIT {$offset},{$size}";
        }
        $rows = $db->fetchAll($query);
        return [
            'page'      => $page,
            'totalPage' => ceil($total / $size),
            'size'      => $size,
            'total'     => $total,
            'rows'      => $rows
        ];
    }
}
